<?php
try{
	include '../ini.php';
    include '../classes/xl_product.php';
    $dt_xl_product=new xl_product;
    if(empty($_GET['id'])){
        throw new Exception('Không tồn tại mã này');
    }
    $read_product=$dt_xl_product->read_id($_GET['id']);
    if($read_product === false){
        throw new Exception('Không tồn tại mã này');
    }
    if($_GET['id'] != $read_product['id']){
        $_GET['id']=$dt_xl_admin->removeSQLI($_GET['id']);
        header("Location: product_update.php?id=".$_GET['id']);
    }
    $list_product=$dt_xl_product->read_category();
    $list_brand=$dt_xl_product->read_brand();
    function print_list($list,$id,$characters,$id_select) {
        $str='';
    	foreach ($list as $location){
    		if ($location['parent'] == $id):
    			if ($location['id'] == $id_select){		
    				$str.= '<option selected="selected" value="'.$location['id'].'">'.$characters.$location['name'].'</option>';
    			} else{
    				$str.= '<option value="'.$location['id'].'">'.$characters.$location['name'].'</option>';
    			} 
    		    print_list($list, $location['id'], $characters.$characters, $id_select);
    		endif;
        }
        return $str;
    }
    function print_list_brand($list,$characters,$id_select) {
        $str='';
    	foreach ($list as $location){
			if ($location['id'] == $id_select){		
				$str.= '<option selected="selected" value="'.$location['id'].'">'.$characters.$location['name'].'</option>';
			} else{
				$str.= '<option value="'.$location['id'].'">'.$characters.$location['name'].'</option>';
			} 
        }
        return $str;
    }
    
    
    $read_product_images=$dt_xl_product->delete_all_product_images($_GET['id']);
    foreach($read_product_images as $list){
         $dt_smarty->assign('list_product_image',$list);
    }
    $dt_smarty->assign('list_product',$list_product);
    $dt_smarty->assign('list_brand',$list_brand);
    $dt_smarty->assign('read_product',$read_product);
	$contenForLayout=$dt_smarty->fetch('product/product_update.tpl');
	$dt_smarty->assign('contenForLayout',$contenForLayout);
	$dt_smarty->assign('titleForLayout','Chỉnh sửa sản phẩm');
	$dt_smarty->display('layout/defaults.tpl');
    $dbh=NULL;
	
} catch(Exception $e){
    $dbh=NULL;
	$_SESSION['msg']=$e->getMessage();
    $_SESSION['type_msg']='error';
    if(empty($_SERVER['HTTP_REFERER'])){
        header('Location: product_list.php');
    }else{
        header('Location:'.$_SERVER['HTTP_REFERER']);
    }
   
}
